package day7;

import java.util.Arrays;

public class ch1 {

    public int numIslands(char[][] grid) {
        int sum = 0;

        boolean[][] bool = new boolean[grid.length][grid[0].length];
        Arrays.fill(bool,false);
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if(grid[i][j]=='1'&&!bool[i][j]){
                    sum += 1;
                    dfs(i,j,bool,grid);
                }
            }
        }
        return sum;
    }


    public void dfs(int i,int j,boolean[][] bool,char[][] grid){
        if(i<0||i>=bool.length) return;
        if(j<0||j>=bool[0].length) return;
        if(grid[i][j]=='0') return;
        if(bool[i][j]) return;

        bool[i][j] = true;
        dfs(i+1,j,bool,grid);
        dfs(i,j-1,bool,grid);
        dfs(i-1,j,bool,grid);
        dfs(i,j+1,bool,grid);

    }



    public int orangesRotting(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;

        int sum = 0;




        while (sum<(m+n)){
            if(cal(grid)) return sum;
            sum += 1;
            int[][] arr = new int[m][n];
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if(grid[i][j]==2 && arr[i][j]==0){
                        fun(i+1,j,grid,arr);
                        fun(i-1,j,grid,arr);
                        fun(i,j+1,grid,arr);
                        fun(i,j-1,grid,arr);
                    }
                }
            }
        }

        return sum;



    }

    public boolean cal(int[][] grid){
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if(grid[i][j]==1) return false;
            }
        }
        return true;

    }

    public void fun(int i,int j,int[][] grid,int[][] arr){
        if(i<0||i>=grid.length) return;
        if(j<0||j>=grid[0].length) return;

        if(grid[i][j]==1) {
            grid[i][j]=2;
            arr[i][j]=1;
        }


    }





}
